package com.wchen.gdoc.generate.resource.loader;

import com.alibaba.fastjson.JSONObject;
import com.sun.javadoc.*;
import com.wchen.gdoc.generate.config.ApplicationConfig;
import com.wchen.gdoc.generate.config.ApplicationConfigProvide;
import com.wchen.gdoc.generate.resource.analysis.ClassDocAnalysis;
import com.wchen.gdoc.generate.resource.structure.ClassStructure;
import com.wchen.gdoc.generate.util.FilePathUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.*;

/**
 * javadoc扫描
 *
 * @author  wchen
 * @date    2019/11/7
 */
public class JavaDocScanningProvider extends Doclet {
    protected final static Logger LOGGER = LoggerFactory.getLogger(JavaDocScanningProvider.class);
    private final static List<ClassStructure> CLASS_STRUCTURES = new ArrayList<>();
    private final static String JAVA_FILE_SUFFIX = ".java";


    /**
     * 解析doc
     * @param root
     * @return
     */
    public static boolean start(RootDoc root) {
        ClassDocAnalysis classAnalysis = new ClassDocAnalysis();
        ClassDoc[] classes = root.classes();
        for (ClassDoc aClass : classes) {
            ClassStructure classStructure = classAnalysis.analysisClassDoc(aClass);
            CLASS_STRUCTURES.add(classStructure);
        }
        return true;
    }

    /**
     * 指定版本
     * @return
     */
    public static LanguageVersion languageVersion() {
        return LanguageVersion.JAVA_1_5;
    }

    /**
     * 获取解析的结果集
     * @return
     */
    public static List<ClassStructure> getClassStructures(){
        extractDoc();
        return CLASS_STRUCTURES;
    }

    /**
     * 执行javaDoc
     */
    private static void extractDoc(){
        String separator = System.getProperty("file.separator");
        ApplicationConfig applicationConfig = ApplicationConfigProvide.getApplicationConfig();
        String targetScanPath = applicationConfig.getTargetProjectConfig().getTargetScanPath();
        String targetProjectPath = applicationConfig.getTargetProjectConfig().getTargetProjectPath();
        String targetClassPath = applicationConfig.getTargetProjectConfig().getTargetClassPath();
        String[] scanPathList = targetScanPath.split(";");
        List<String> filePathList = new ArrayList<>();
        for (String scanPth : scanPathList) {
            String pendScanPath = targetProjectPath + scanPth.replace(".", separator);
            if(scanPth.endsWith(JAVA_FILE_SUFFIX)){
                String transPath = scanPth.substring(0, scanPth.length() - 5).replace(".", separator) + JAVA_FILE_SUFFIX;
                pendScanPath = targetProjectPath + transPath;
            }
            filePathList.addAll(FilePathUtil.getAllPathFile(pendScanPath, JAVA_FILE_SUFFIX));
        }
        if(filePathList.isEmpty()){
            throw new RuntimeException("There are no available java files ...");
        }
        //添加classPath路径
        String systemClassPath = System.getProperty("java.class.path");
        System.setProperty("java.class.path", systemClassPath + ";" + targetClassPath);

        List<String> docArgsList = new ArrayList<>();
        docArgsList.add("-doclet");
        docArgsList.add(JavaDocScanningProvider.class.getName());
        docArgsList.add("-sourcepath");
        docArgsList.add(targetProjectPath);
        docArgsList.add("-encoding");
        docArgsList.add("UTF-8");
//        docArgsList.add("-charset");
//        docArgsList.add("UTF-8");
        docArgsList.addAll(filePathList);

        LOGGER.info(String.format("extractDoc ags:%s", docArgsList));
        com.sun.tools.javadoc.Main.execute(docArgsList.toArray(new String[docArgsList.size()]));
    }

    public static void main(String[] args) throws Exception{
//        String filePath = "F:\\项目管理\\代码管理\\study\\spring-review\\springmvc-review\\src\\main\\java\\com\\wchen\\springmvc\\review\\web\\CustomerDoclet.java";
//        String filePath = "F:\\PROJECT\\spring-cloud\\spring-review\\gdoc\\src\\main\\java\\com\\wchen\\gdoc\\web\\TestDocController.java";

        String filePath2 = "-sourcepath com\\wchen\\springmvc\\review\\web";
        String[] docArgs =
                new String[]{
                        "-doclets", JavaDocScanningProvider.class.getName(),

                        "-sourcepath",
                        "F:\\项目管理\\代码管理\\work\\xianchao\\app\\src\\main\\java\\",
////                        "F:\\项目管理\\代码管理\\study\\spring-review\\springmvc-review\\src\\main\\java\\com\\wchen\\springmvc\\review\\web\\UserController.java"
//                        ,
                        "-encoding",
                        "UTF-8",
//                        "-charset",
//                        "UTF-8",
//                        "com.wchen.springmvc.review.web.CustomerDoclet"
                        "com.ald.sectrade.app.controller.IndexController"
//                        filePath
                };
//        ClassLoader appClassLoader = Thread.currentThread().getContextClassLoader();
        List<ClassStructure> getClassStructures = getClassStructures();
        for (ClassStructure getClassStructure : getClassStructures) {
            System.out.println(JSONObject.toJSONString(getClassStructure, true));
        }

    }
}